<route>
{
  "layout": "default",
  "style": {
    "navigationStyle": "custom"
  }
}
</route>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import type { IFamilyMember } from '@/api/types/family';
import { addFamilyMember, updateFamilyMember, deleteFamilyMember } from '@/api/family';

// 表单数据
const form = ref<{name: string, idCard: string, gender: 'male' | 'female', isDefault: boolean}>({
  name: '',
  idCard: '',
  gender: 'male',
  isDefault: false
});

// 是否为编辑模式
const isEdit = ref(false);
// 当前编辑的患者信息
const patientInfo = ref<IFamilyMember | null>(null);

// 页面加载时初始化
onMounted(() => {
  // 获取当前页面的eventChannel
  const eventChannel = getCurrentPages().at(-1)?.getOpenerEventChannel();
  if (eventChannel) {
    // 监听editData事件
    eventChannel.on('editData', (data: {isEdit: boolean, patientInfo: IFamilyMember}) => {
      isEdit.value = data.isEdit;
      patientInfo.value = data.patientInfo;
      
      // 初始化表单数据
      if (patientInfo.value) {
        form.value = {
          name: patientInfo.value.name || '',
          idCard: patientInfo.value.idCard || '',
          gender: patientInfo.value.gender === '男' ? 'male' : 'female',
          isDefault: patientInfo.value.isDefault || false
        };
      }
    });
  }
});

// 返回家庭档案页面
const goBack = () => {
  uni.navigateBack();
};

// 保存患者信息
const savePatient = async () => {
  // 表单验证
  if (!form.value.name || !form.value.idCard) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }

  try {
    if (isEdit.value && patientInfo.value) {
      // 编辑患者
      const updateData = {
        id: patientInfo.value.id,
        name: form.value.name,
        idCard: form.value.idCard,
        gender: form.value.gender === 'male' ? 1 : 0,
        defaultFlag: form.value.isDefault ? 1 : 0
      };

      const res = await updateFamilyMember(updateData);
      if (res.code === 10000) {
        uni.showToast({
          title: '编辑成功',
          icon: 'success'
        });
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        uni.showToast({
          icon: 'none',
          title: res.message || '编辑失败'
        });
      }
    } else {
      // 添加患者
      const addData = {
        name: form.value.name,
        idCard: form.value.idCard,
        gender: form.value.gender === 'male' ? 1 : 0,
        defaultFlag: form.value.isDefault ? 1 : 0
      };

      const res = await addFamilyMember(addData);
      if (res.code === 10000) {
        uni.showToast({
          title: '添加成功',
          icon: 'success'
        });
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        uni.showToast({
          icon: 'none',
          title: res.message || '添加失败'
        });
      }
    }
  } catch (error) {
    console.error('保存患者信息失败:', error);
    uni.showToast({
      icon: 'none',
      title: '网络错误，请稍后重试'
    });
  }
};

// 删除患者
const deletePatient = () => {
  if (!isEdit.value || !patientInfo.value?.id) {
    return;
  }

  uni.showModal({
    title: '确认删除',
    content: '确定要删除该患者信息吗？',
    success: function(res) {
      if (res.confirm) {
        deleteFamilyMember(patientInfo.value!.id)
          .then(res => {
            if (res.code === 10000) {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              setTimeout(() => {
                goBack();
              }, 1500);
            } else {
              uni.showToast({
                icon: 'none',
                title: res.message || '删除失败'
              });
            }
          })
          .catch(error => {
            console.error('删除患者信息失败:', error);
            uni.showToast({
              icon: 'none',
              title: '网络错误，请稍后重试'
            });
          });
      }
    }
  });
};
</script>

<template>
  <view class="patient-form-container">
    <view class="form-header">
      <view class="back-btn" @click="goBack">
        <img src="/static/image/return@1x.png" alt="返回" style="width: 20px; height: 20px">
      </view>
      <view class="header-title">{{ isEdit ? '编辑患者' : '添加患者' }}</view>
      <view class="save-btn" @tap="savePatient">保存</view>
    </view>

    <view class="form-body">
      <view class="form-item" style="border-bottom: 1px solid #f5f5f5;">
        <view class="form-label">真实姓名</view>
        <input class="form-input" v-model="form.name" placeholder="请输入真实姓名" />
      </view>
      <view class="form-item" style="border-bottom: 1px solid #f5f5f5;">
        <view class="form-label">身份证号</view>
        <input class="form-input" v-model="form.idCard" placeholder="请输入身份证号" />
      </view>
      <view class="form-item">
        <view class="form-label">性别</view>
        <view class="gender-selector">
          <view class="gender-btn" :class="{ 'selected': form.gender === 'male' }" @click="form.gender = 'male'">男</view>
          <view class="gender-btn" :class="{ 'selected': form.gender === 'female' }" @click="form.gender = 'female'">女</view>
        </view>
      </view>
      <view class="form-item" style="border-top: 1px solid #f5f5f5;padding-top: 40rpx;">
        <view class="checkbox-text" @click="form.isDefault = !form.isDefault">默认就诊人</view>
        <view class="checkbox" :class="{ 'checked': form.isDefault }"></view>
      </view>
    </view>

    <view class="form-footer">
      <button class="delete-btn" @tap="deletePatient" v-if="isEdit">删除</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.patient-form-container {
  padding: 20rpx;
  box-sizing: border-box;
  min-height: 100vh;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid #eee;
  margin-bottom: 30rpx;
}

.header-title {
  font-size: 39rpx;
  font-weight: bold;
  margin-bottom: 14rpx;
}

.save-btn {
//   padding: 10rpx 20rpx;
//   height: 60rpx;
  border: none;
//   border-radius: 8rpx;
//   background-color: #11c1a2;
  color: #11c1a2;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-body {
  padding: 0 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  justify-content: left;
}

.form-label {
    width: 200rpx;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  margin-top: 15rpx;
  padding-top: 6rpx;
  padding-bottom: 33rpx;
}

.form-input {
  width: 90%;
  height: 80rpx;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.gender-selector {
  display: flex;
  align-items: center;
}

.gender-option.selected {
  border-color: #11c1a2;
  background-color: #11c1a2;
}

.gender-selector {
  display: flex;
  align-items: center;
  margin-top: 15rpx;
}

.gender-btn {
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
  height: 70rpx;
  line-height: 30rpx;
//   border: 2rpx solid #ccc;
background-color: #eee;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.gender-btn.selected {
  background-color: #eaf8f6;
  border:2rpx solid #11c1a2;
  color: #333;
}

.checkbox {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #ccc;
  border-radius: 8rpx;
  display: inline-block;
  margin-right: 10rpx;
  vertical-align: middle;
}

.checkbox.checked {
  border-color: #11c1a2;
  background-color: #11c1a2;
  position: relative;
}

.checkbox.checked::after {
  content: '✓';
  color: white;
  font-size: 20rpx;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.checkbox-text {
    width: 200rpx;
  font-size: 28rpx;
  color: #333;
  display: inline-block;
  vertical-align: middle;
}

.form-footer {
  padding: 20rpx;
  margin-top: 40rpx;
}

.delete-btn {
  width: 100%;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  background-color: #f6f7f9;
  color: #ff4d4f;
  font-size: 32rpx;
  margin-top: 610rpx;
}
</style>